package com.samphanie.dries.ui.home;

import android.util.Log;

import androidx.annotation.NonNull;
import androidx.paging.DataSource;
import androidx.paging.ItemKeyedDataSource;

import com.alibaba.fastjson.TypeReference;
import com.samphanie.dries.AbsViewModel;
import com.samphanie.dries.model.Feed;
import com.samphanie.lib.network.ApiResponse;
import com.samphanie.lib.network.ApiService;
import com.samphanie.lib.network.JsonCallback;
import com.samphanie.lib.network.Request;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

public class HomeViewModel extends AbsViewModel<Feed> {

    private volatile boolean withCached = true;
    private AtomicBoolean loadAfter = new AtomicBoolean(false);
    private String mFeedType;

    @Override
    public DataSource createDataSource() {
        return mDataSource;
    }

    public void setFeedType(String feedType) {
        this.mFeedType = feedType;
    }

    ItemKeyedDataSource<Integer, Feed> mDataSource = new ItemKeyedDataSource<Integer, Feed>() {
        /**
         * 初始化数据
         * @param params
         * @param callback
         */
        @Override
        public void loadInitial(@NonNull LoadInitialParams<Integer> params, @NonNull LoadInitialCallback<Feed> callback) {
            loadData(0,  params.requestedLoadSize, callback);
            withCached = false;
        }

        /**
         * 加载分页数据
         * @param params
         * @param callback
         */
        @Override
        public void loadAfter(@NonNull LoadParams<Integer> params, @NonNull LoadCallback<Feed> callback) {
            loadData(params.key, params.requestedLoadSize, callback);
        }

        /**
         * 向前加载数据
         * @param params
         * @param callback
         */
        @Override
        public void loadBefore(@NonNull LoadParams<Integer> params, @NonNull LoadCallback<Feed> callback) {
            callback.onResult(Collections.emptyList());
        }

        /**
         *
         * @param item
         * @return
         */
        @NonNull
        @Override
        public Integer getKey(@NonNull Feed item) {
            return item.getId();
        }
    };

    private void loadData(int key, int count,  ItemKeyedDataSource.LoadCallback<Feed> callback) {
//        if (key > 0) {
//            loadAfter.set(true);
//        }
        Request request = ApiService.get("/feeds/queryHotFeedsList")
                .addParam("feedType", mFeedType)
                .addParam("userId", 0)
                .addParam("feedId", key)
                .addParam("pageCount", count)
                .responseType(new TypeReference<ArrayList<Feed>>() {
                }.getType());

        if (withCached) {
            request.setmCacheStrategy(Request.CACHE_ONLY);
            request.excute(new JsonCallback<List<Feed>>() {
                @Override
                public void onCacheSuccess(ApiResponse<List<Feed>> response) {
                    Log.e("onCacheSuccess", "onCacheSuccess" + response.getData().toString());
                }
            });
        }

        try {
            Request netRequest = withCached ? request.clone() : request;
            netRequest.setmCacheStrategy(key == 0 ? Request.NET_CACHE : Request.NET_ONLY);
            ApiResponse<List<Feed>> response = netRequest.excute();
            List<Feed> feeds = null;
            if (response.getData() == null) {
                feeds = new ArrayList<>();
            } else {
                feeds = response.getData();
            }

            callback.onResult(feeds);

            if (key > 0) {
                // 通过getMutableLiveData发送数据 告诉UI层 是否应该主动关闭上拉加载分页的动画
                getMutableLiveData().postValue(feeds.size() > 0);
                // loadAfter.set(false);
            }

        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }

    }

//    public void loadAfter(int id, ItemKeyedDataSource.LoadCallback<Feed> callback) {
//        if (loadAfter.get()) {
//            callback.onResult(Collections.emptyList());
//            return;
//        }
//        ArchTaskExecutor.getIOThreadExecutor().execute(new Runnable() {
//            @Override
//            public void run() {
//                loadData(id, config.pageSize, callback);
//            }
//        });
//    }

}